package edu.hawaii.halealohacli.command;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimerTask;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.resource.sensordata.jaxb.SensorData;
/**
 * Implements the TimerTask class and uses the existing
 * CurrentPower class to print current power on an interval.
 * 
 * @author Alex
 *
 */
public class MonitorGoalTask extends TimerTask {
  private WattDepotClient client;
  private String source;
  private int goal;
  private List<Double> list;
 
  /**
   * MonitorGoalTask constructor.
   * @param source Source input from the user.
   * @param client WattDepot client to connect to.
   * @param goal The % reduction of the baseline
   * @param list The current baseline of the source
   */
  public MonitorGoalTask(String source, WattDepotClient client, int goal, List<Double> list) {
    this.client = client;
    this.source = source;
    this.goal = goal;
    this.list = list;
  }
  
  /**
   * Get the current time.
   * @return the current time.
   */
  public String getCurrentTime () {
    Calendar calendar = new GregorianCalendar();
    SimpleDateFormat checkTime = new SimpleDateFormat("HH:mm:ss", Locale.US);
    return checkTime.format(calendar.getTime());
  }
  
  @Override
  public void run() {
    SensorData data = null;
    double currentPower = 0;
    
    // Get the current power.
    try {
      data = this.client.getLatestSensorData(this.source);
      XMLGregorianCalendar timestamp = data.getTimestamp();
      currentPower = this.client.getPowerConsumed(this.source, timestamp) / 1000;
    }
    catch (NotAuthorizedException e) {
      System.out.println("You are not allowed to access this client");
    }
    catch (ResourceNotFoundException e) {
      System.out.println("\"" + this.source + "\" is not a valid source.");
    }
    catch (WattDepotClientException e) {
      System.out.println("An unexpected error occured. Please try again.");
    }
    int hour = data.getTimestamp().getHour();
    double goalPower = list.get(hour) * (100 - this.goal) / 100;
    System.out.printf("%-10s %-15.2f %-18.2f %-14.2f %-15s %n", 
        getCurrentTime(), 
        currentPower, 
        list.get(hour), 
        goalPower, 
        (currentPower <= goalPower) ? "yes" : "no");
  }
}